package com.marver.common.enumeration;

import com.marver.common.dao.BaseDAOImpl;
import com.marver.entity.Wordbook;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@SuppressWarnings("unchecked")
@Service
public class LabeledEnumResolver extends BaseDAOImpl {
    protected static Map<String,StringLabeledEnum> CODE_MAP_CACHE = Collections.synchronizedMap(new HashMap<String,StringLabeledEnum>());
    protected static Map<String,HashMap<String,StringLabeledEnum>> CATEGORY_MAP_INDEX = Collections.synchronizedMap(new HashMap<String,HashMap<String,StringLabeledEnum>>());
    
    public LabeledEnumResolver(){
    	
    }
    
    public void initEnums(){
        long startTime = System.currentTimeMillis();
        logger.info("Start to load all the msgcodes from database........ " + startTime);
        
		List<Wordbook> wbs = (List<Wordbook>)this.listBySqlMap("params.getAllWordBook", null);
        logger.info("All msgcodes was loaded ........ cost:" + (System.currentTimeMillis() - startTime));
        if(wbs == null)
            return;
        long cacheTime = System.currentTimeMillis();
        logger.info("Put all msgcodes to cache process starting ........ at " + cacheTime);
        for(Wordbook wb:wbs)
        {
            String category = wb.getParamType();
            String msgcode = wb.getParamCode();
            String translation = wb.getParamValue();
            if(StringUtils.hasText(category))
            {
            	StringLabeledEnum sl=new StringLabeledEnum(translation, msgcode, category);
                if(!CATEGORY_MAP_INDEX.containsKey(category))
                    CATEGORY_MAP_INDEX.put(category, new HashMap<String,StringLabeledEnum>());
                //if(!CODE_MAP_CACHE.containsKey(msgcode))
                CODE_MAP_CACHE.put(msgcode, sl);
                ((Map<String,StringLabeledEnum>)CATEGORY_MAP_INDEX.get(category)).put(msgcode, sl);
            }
        } 
    }
    
    public StringLabeledEnum getStringLabeledEnum(String msgcode){
    	return CODE_MAP_CACHE.containsKey(msgcode)?CODE_MAP_CACHE.get(msgcode):null;
    }
    
    public Map<String,StringLabeledEnum> getCategory(String msgcode){
    	return CATEGORY_MAP_INDEX.containsKey(msgcode)?CATEGORY_MAP_INDEX.get(msgcode):null;
    }
}
